<?php

/**
 * Created by PhpStorm.
 * User: yutongfu
 * Date: 2019/6/23
 * Time: 11:29 AM
 */
class test
{
    public $index = 0;
}

class Server
{
    private $serv;

    public function __construct()
    {
        //构建Server对象
        $this->serv = new Swoole\Server('0.0.0.0', 9501, SWOOLE_BASE, SWOOLE_SOCK_TCP);
        //设置运行时参数
        $this->serv->set([
            'work_num' => 8,
            'daemonize' => false,
            'max_request' => 10000,
            'dispatcg' => 2,
            'task_worker_num' => 8 //有这个参数就必须有task方法
        ]);
        //注册事件回调函数
        $this->serv->on('Start', [$this, 'onStart']);
        $this->serv->on('Connect', [$this, 'onConnect']);
        $this->serv->on('Receive', [$this, 'onReceive']);
        $this->serv->on('Close', [$this, 'onClose']);
        //bind callback
        $this->serv->on('Task', [$this, 'onTask']);
        $this->serv->on('Finish', [$this, 'onFinish']);
        $this->serv->start();

    }

    public function onStart($serv)
    {
        echo "Start\n";
    }

    public function onConnect($serv, $fd, $from_id)
    {
        echo "Client {$fd} connect\n";
    }

    public function onClose($serv, $fd, $from_id)
    {
        echo "Client {$fd} close connect\n";
    }

    public function onReceive(swoole_server $serv, $fd, $form_id, $data)
    {
        echo "Get Message From Client {$fd}:{$data}\n";

        $data = [
            'task' => 'task_1',
            'params' => $data,
            'fd' => $fd
        ];
        $serv->task(json_encode($data));//task方法只能传字符串
    }

    public function onTask(swoole_server $serv, $task_id, $from_id, $data)
    {
        echo "This Task {$task_id} From Worker {$from_id}\n";
        echo "data:{$data}\n";
        $data = json_decode($data, true);
        echo "Receive Task :{$data['task']}\n";
        var_dump($data['params']);
        $serv->send($data['fd'], 'Hello Task');
        return 'Finished';
    }

    public function onFinish($serv,$task_id,$data)
    {
        echo "Task {$task_id} finish\n";
        echo "Result :{$data}\n";
    }


}
$server = new Server();